#include	"Http.h"

#include	<Logger.h>
#include	<curl/curl.h>

void Http::Start(const std::string & url, const std::string & param, bool post /* = false */) {
	static Runnable<Http> works(16);

	_url = url;
	_param = param;
	_post = post;

	works.AddRunnable(this);
}

size_t Http::__HandleResponse(void * data, size_t size, size_t count, void * userdata) {
	Http * p = (Http *)userdata;
	std::string response((char *)data, size * count);
	if (p->_response) p->_response(response);
	return size * count;
}

void Http::Run() {
	CURL * ctx = curl_easy_init();
	if (ctx == nullptr) {
		LOG_ERR("HTTP request failed. Due to curl_easy_init");
		if (_error) _error();
		return;
	}

	if (_post) {
		curl_easy_setopt(ctx, CURLOPT_POST, 1);
		curl_easy_setopt(ctx, CURLOPT_URL, _url.c_str());
		curl_easy_setopt(ctx, CURLOPT_POSTFIELDS, _param.c_str());
	} else {
		std::string url = _url + "?" + _param;
		curl_easy_setopt(ctx, CURLOPT_POST, 0);
		curl_easy_setopt(ctx, CURLOPT_URL, url.c_str());
	}

	curl_easy_setopt(ctx, CURLOPT_TIMEOUT, 3);
	curl_easy_setopt(ctx, CURLOPT_VERBOSE, 0);
	curl_easy_setopt(ctx, CURLOPT_WRITEFUNCTION, Http::__HandleResponse);
	curl_easy_setopt(ctx, CURLOPT_WRITEDATA, this);
	curl_easy_setopt(ctx, CURLOPT_SSL_VERIFYPEER, 0);
	curl_easy_setopt(ctx, CURLOPT_SSL_VERIFYHOST, 0);
	curl_easy_setopt(ctx, CURLOPT_HEADER, 0);
	curl_easy_setopt(ctx, CURLOPT_NOSIGNAL, 1L);

	CURLcode ret = curl_easy_perform(ctx);
	if (ret != CURLE_OK) {
		LOG_ERR("HTTP request failed. Due to curl_easy_perform ret : %d, %s", ret, curl_easy_strerror(ret));
		if (_error) _error();
	}
}